package com.whq.knowverywell.business.http;

import org.json.JSONObject;

import android.content.Context;

import com.whq.knowverywell.business.LoginUtil;
import com.whq.knowverywell.business.model.Product;
import com.whq.knowverywell.util.LogUtil;
import com.whq.knowverywell.util.NetworkUtil;
import com.whq.knowverywell.util.StringUtil;
import com.whq.knowverywell.util.constant.CfgConstant;
import com.whq.knowverywell.util.httpclient.HttpClientUtil;
import com.whq.knowverywell.util.httpclient.HttpResult;

/**
 * 根据条形码获取单个商品的信息
 * @author wanghuaiqiang
 *
 */
public class GetProductDataUtil {
	private static final String TAG = "GetProductDataUtil";
	
	public static Product getDetail(Context context, String productBarcode) {
		Product retObj = null;
		if (context == null) {
			return retObj;
		}
		if (!NetworkUtil.isNetworkAvailable(context)) {
			return retObj;
		}
		
		String token = LoginUtil.getLoginToken(context);
		if (StringUtil.isBlank(token)) {
			return retObj;
		}
		
		// 获取guid
		String path = CfgConstant.SERVER_CONTEXT + "/product/detail";
		StringBuilder sb = new StringBuilder();
		sb.append("token=" + token);
		sb.append("&productBarcode=" + productBarcode);
		sb.append("&version=" + CfgConstant.SERVER_API_VERSION);
		sb.append("&source=" + CfgConstant.SERVER_API_SOURCE);
		
		String req = sb.toString();
		HttpResult httpResult = HttpClientUtil.callServer(context, CfgConstant.SERVER_HOST, false, path, req, "UTF-8");
		if ( (httpResult == null) 
				|| (!httpResult.checkCode()) 
				) {
			return retObj;
		}
		
		String responseStr = httpResult.getResp();
		if (StringUtil.isBlank(responseStr)) {
			return retObj;
		}
		
		try {
			JSONObject recordJson = new JSONObject(responseStr);
			int resultCode = recordJson.optInt("resultCode", -1);
			if (resultCode != 0) {
				ChkResponseUtil.chkLogoutErrorCode(context, resultCode);
				return retObj;
			}
			
			if (recordJson.isNull("data")) {
				return retObj;
			}
			
			JSONObject dataJson = recordJson.getJSONObject("data");
				
			retObj = new Product();
			retObj.setBarCode(dataJson.optString("BarCode", ""));
			retObj.setCode(dataJson.optString("Code", ""));
			retObj.setName(dataJson.optString("Name", ""));
			retObj.setImgUrl(dataJson.optString("ImgUrl", ""));
			retObj.setPrice(dataJson.optDouble("Price", 10));
			retObj.setShellFabric(dataJson.optString("ShellFabric", ""));
				
		} catch (Exception e) {
			LogUtil.e(TAG, "解析json串出错：", e);
		}
		return retObj;
	}
	
}
